package test;

import java.io.IOException;  
import java.net.InetSocketAddress;  
import java.nio.ByteBuffer;  
import java.nio.channels.SelectionKey;  
import java.nio.channels.Selector;  
import java.nio.channels.SocketChannel;  
import java.util.Scanner;  
  
/** 
 * 客户端 
 * @author Administrator 
 * 
 */  
public class Client {  
    private Selector selector;  
    SocketChannel socketchannel;  
    private String hostIp;  
    private int port;  
    /** 
     * 构造函数 
     * @param hostIp 
     * @param port 
     * @throws IOException 
     */  
    public Client (String hostIp,int port)throws IOException{  
        this.hostIp = hostIp;  
        this.port = port;  
          
        initialize();  
    }  
    /** 
     * 初始化 
     * @throws IOException 
     */  
    public void initialize() throws IOException{  
        //打开监听信道并设置为非阻塞模式  
        socketchannel = SocketChannel.open(new InetSocketAddress(hostIp,port));  
        socketchannel.configureBlocking(false);  
        //打开并注册到信道  
        selector = Selector.open();  
        socketchannel.register(selector, SelectionKey.OP_READ);  
        //启动读线程  
        new ClientThread(selector);  
    }  
      
    public void sendMsg(String message)throws IOException{  
        ByteBuffer writeBuffer = ByteBuffer.wrap(message.getBytes("UTF-16"));  
        socketchannel.write(writeBuffer);  
    }  
    public static void main(String[] args)throws IOException{  
        Client client = new Client("127.0.0.1",10005);  
        Scanner read = new Scanner(System.in);  
        while(true){  
            System.out.println("本地:");  
            String msg = read.next();  
            client.sendMsg(msg);  
        }  
    }  
}  